from django.conf import settings
from .models import UserPoints, PointsRecord


def award_points(user, point_type, description, activity_id=None):
    """奖励积分
    
    Args:
        user: 用户对象
        point_type: 积分类型
        description: 描述
        activity_id: 活动ID（用于评论积分，确保每个活动每个用户只能获得一次评论积分）
    """
    points_config = settings.POINTS_CONFIG
    points = points_config.get(point_type, 0)
    
    if points == 0:
        return 0
    
    # 如果是评论积分且指定了activity_id，检查是否已经获得过该活动的评论积分
    if point_type == 'comment' and activity_id:
        existing_record = PointsRecord.objects.filter(
            user=user,
            type='comment',
            activity_id=activity_id
        ).exists()
        
        if existing_record:
            # 已经获得过该活动的评论积分，不再奖励
            return 0
    
    # 获取或创建用户积分记录
    user_points, created = UserPoints.objects.get_or_create(user=user)
    
    # 更新积分
    user_points.total_points += points
    user_points.available_points += points
    user_points.save()
    
    # 创建积分记录
    PointsRecord.objects.create(
        user=user,
        points=points,
        type=point_type,
        description=description,
        activity_id=activity_id
    )
    
    return points


def deduct_points(user, points, description, action_type='exchange'):
    """
    扣除用户积分 - 适配新的积分系统
    """
    from .models import UserPoints, PointsRecord

    # 获取用户积分
    user_points, created = UserPoints.objects.get_or_create(user=user)

    # 确保积分不会变成负数
    actual_deduction = min(points, user_points.available_points)

    if actual_deduction > 0:
        # 更新用户积分
        user_points.total_points -= actual_deduction
        user_points.available_points -= actual_deduction
        user_points.used_points += actual_deduction
        user_points.save()

        # 创建积分记录
        PointsRecord.objects.create(
            user=user,
            points=-actual_deduction,  # 负数表示扣除
            type=action_type,
            description=description
        )

        return True
    else:
        return False
